package org.csu.mypetstore.web.servlets;

import org.apache.commons.beanutils.BeanUtils;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.SignOn;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;

@WebServlet("/signOn")
public class SignInServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        String verifycode = req.getParameter("verifycode");
        //校验验证码
        HttpSession session = req.getSession();
        String checkcood_server = (String) session.getAttribute("CHECKCODE_SERVER");
        //保证验证码是一次性的
        session.removeAttribute("CHECKCODE_SERVER");
        if(!checkcood_server.equalsIgnoreCase(verifycode)){
            //验证码不正确
            req.setAttribute("login_msg","验证码错误！请重新输入！");
            req.getRequestDispatcher("/WEB-INF/jsp/account/SignonForm.jsp").forward(req,resp);

            return;
        }
        Map<String, String[]> map = req.getParameterMap();
        SignOn user = new SignOn();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        AccountService service = new AccountService();
        SignOn loginuser = service.login(user);
        if (loginuser!=null){
            //登录成功
            req.getSession().setAttribute("user",loginuser);
            LogService logService = new LogService();
            Date time = new Date();
            String logmsg = "登录成功";
            logService.insertLog_signin(loginuser.getUsername(),logmsg,time);
            req.getSession().setAttribute("account",service.getAccount(loginuser.getUsername()));
            System.out.println("登录成功");
            req.getRequestDispatcher("/WEB-INF/jsp/catalog/Main.jsp").forward(req,resp);

        }else {
            req.setAttribute("login_msg","用户名或密码错误！");
            req.getRequestDispatcher("/WEB-INF/jsp/account/SignonForm.jsp").forward(req,resp);
        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
